import { history } from '@umijs/max'
import { LOGIN_PAGES } from './constants'
import { cleanMenuData, getInitData } from './utils/getMenuInfo'
import { MenuAll } from './services/common'
import { LoginType } from './pages/Login/services'

// 运行时配置
window.__tempParams = {}

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState(): Promise<InitialState> {
  if (LOGIN_PAGES.includes(history.location.pathname)) {
    return { menuList: [] }
  }

  if (sessionStorage.userId || sessionStorage.username) {
    const res = await getInitData(
      sessionStorage.userType === String(LoginType.大客户登录) ? MenuAll.大客户可见菜单 : MenuAll.平台可见菜单, 
      sessionStorage.userType === String(LoginType.大客户登录) ? localStorage.Authorization2 : undefined
    )

    if (res) {
      const menuList = cleanMenuData(res[0].data)
      return {
        menuList,
      }
    }
  }

  let originHref: string
  if (window.location.href.includes('redirect=')) {
    originHref = window.location.href.split('redirect=').at(-1) || '/'
  } else {
    originHref = encodeURIComponent(window.location.href)
  }
  history.replace(`${LOGIN_PAGES[sessionStorage.userType === String(LoginType.大客户登录) ? 1 : 0]}?redirect=${originHref}`)

  return { menuList: [] }
}
